# --utf-8--
import re
import time
# import browser_cookie3
import excel3
from pip._vendor import requests
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from bs4 import BeautifulSoup
from datetime import datetime

# 加载启动项，这里设置headless，表示不启动浏览器，只开一个监听接口获取返回值
option = webdriver.ChromeOptions()
option.add_argument('headless')

s = Service(r"D:\chrome\chromedriver.exe")
driver = webdriver.Chrome(service=s, chrome_options=option)
driver.implicitly_wait(3)  # 隐式等待3秒

"""
  全局变量
"""
sum = 0
Login_URL = r'http://114.116.64.11:8025/Login.aspx'
Source_URL = r'http://114.116.64.11:8025/WebForm5.aspx'
VIEWSTATE = ''
VIEWSTATEGENERATOR = ''
EVENTVALIDATION = ''
GLOBLE_COOKIE = ''


def RET_VIEWSTATE_FUNC(rq):
  RET_VIEWSTATE = re.findall(r'<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="(.*?)" />',
                             rq.content.decode('utf-8'), re.I)
  RET_VIEWSTATEGENERATOR = re.findall(
    r'<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="(.*?)" />',
    rq.content.decode('utf-8'), re.I)
  RET_EVENTVALIDATION = re.findall(
    r'<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="(.*?)" />',
    rq.content.decode('utf-8'), re.I)
  # print(RET_VIEWSTATE, "----")
  # print(RET_VIEWSTATEGENERATOR, "-----")
  # print(RET_EVENTVALIDATION, "-----")
  global VIEWSTATE, VIEWSTATEGENERATOR, EVENTVALIDATION
  VIEWSTATE = RET_VIEWSTATE
  VIEWSTATEGENERATOR = RET_VIEWSTATEGENERATOR
  EVENTVALIDATION = RET_EVENTVALIDATION


def GET_VIEWSTATE_Function():
  get_headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.0.0',
    'Cookie': GLOBLE_COOKIE
  }
  print("123")

  # print("CETcookie",GLOBLE_COOKIE)
  # print("Getheader",get_headers)
  get_rq = requests.get(Source_URL, headers=get_headers)
  # print("GET请求内容",get_rq.content.decode('utf-8'))
  RET_VIEWSTATE_FUNC(get_rq)

# 
def POST_VIEWSTATE_Function_month(EVENTTARGET_month, EVENTARGUMENT_month):
  get_headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.0.0',
    'Cookie': GLOBLE_COOKIE
  }
  POST_values = {}
  global VIEWSTATE, VIEWSTATEGENERATOR, EVENTVALIDATION
  POST_values['__EVENTTARGET'] = EVENTTARGET_month
  POST_values['__EVENTARGUMENT'] = EVENTARGUMENT_month
  POST_values['__VIEWSTATE'] = VIEWSTATE[0]
  POST_values['__VIEWSTATEGENERATOR'] = VIEWSTATEGENERATOR[0]
  POST_values['__EVENTVALIDATION'] = EVENTVALIDATION[0]
  POST_values['ctl00$ContentPlaceHolder1$DropDownList2'] = '--'
  POST_values['ctl00$ContentPlaceHolder1$DropDownList1'] = '--'
  post_req = requests.post(Source_URL, data=POST_values, headers=get_headers)
  # print(post_req.content.decode('utf-8'))
  RET_VIEWSTATE_FUNC(post_req)


def POST_VIEWSTATE_Function_day(EVENTTARGET_Day, EVENTARGUMENT_Day):
  get_headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.0.0',
    'Cookie': GLOBLE_COOKIE
  }
  POST_values = {}
  global VIEWSTATE, VIEWSTATEGENERATOR, EVENTVALIDATION
  POST_values['__EVENTTARGET'] = EVENTTARGET_Day
  POST_values['__EVENTARGUMENT'] = EVENTARGUMENT_Day
  POST_values['__VIEWSTATE'] = VIEWSTATE[0]
  POST_values['__VIEWSTATEGENERATOR'] = VIEWSTATEGENERATOR[0]
  POST_values['__EVENTVALIDATION'] = EVENTVALIDATION[0]
  POST_values['ctl00$ContentPlaceHolder1$DropDownList2'] = '--'
  POST_values['ctl00$ContentPlaceHolder1$DropDownList1'] = '--'
  post_req = requests.post(Source_URL, data=POST_values, headers=get_headers)
  # print(post_req.content.decode('utf-8'))
  RET_VIEWSTATE_FUNC(post_req)


def POST_Search(FilmType, FilmSize):
  get_headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.0.0',
    'Cookie': GLOBLE_COOKIE
  }
  post_values = {}
  global VIEWSTATE, VIEWSTATEGENERATOR, EVENTVALIDATION
  # print("Search",VIEWSTATE)
  post_values['__VIEWSTATE'] = VIEWSTATE[0]
  post_values['__VIEWSTATEGENERATOR'] = VIEWSTATEGENERATOR[0]
  post_values['__EVENTVALIDATION'] = EVENTVALIDATION[0]
  post_values['ctl00$ContentPlaceHolder1$DropDownList2'] = FilmType
  post_values['ctl00$ContentPlaceHolder1$DropDownList1'] = FilmSize
  post_values['ctl00$ContentPlaceHolder1$Button1'] = '查询'
  r2 = requests.post(Source_URL, data=post_values, headers=get_headers)
  # print(r2.content.decode('utf-8'))
  RET_VIEWSTATE_FUNC(r2)
  WEB_jiexi(r2.content.decode('utf-8'), FilmType, FilmSize)


result = []


def WEB_jiexi(dom, var1, var2):
  global sum
  print("开始解析")
  # id ContentPlaceHolder1_TextBox2 <textarea
  # id "ContentPlaceHolder1_TextBox5"
  # id ContentPlaceHolder1_TextBox6
  bs = BeautifulSoup(dom, "html.parser")
  title = bs.find('textarea', id='ContentPlaceHolder1_TextBox2').get_text()
  print(title)
  title2 = bs.find('textarea', id='ContentPlaceHolder1_TextBox5').get_text()
  print(title2)
  title3 = bs.find('textarea', id='ContentPlaceHolder1_TextBox6').get_text()
  print(title3)

  result.append(int(title3))
  sum = sum + int(title3)
  print("和--- ", sum, result)


def EXCEL_FUNCTION(data, var1, var2):
  excel3.Value = data
  excel3.XLWINGS(var1, var2)


def GET_Cookies():
  global GLOBLE_COOKIE
  driver.get(Login_URL)
  driver.find_element(By.XPATH, "//*[@id='TextBox1']").click()
  driver.implicitly_wait(15)
  driver.find_element(By.ID, "TextBox1").clear()
  driver.find_element(By.ID, "TextBox1").send_keys("admin")
  time.sleep(2)
  driver.find_element(By.XPATH, "//*[@id='TextBox2']").click()
  driver.implicitly_wait(2000)
  driver.find_element(By.ID, "TextBox2").clear()
  driver.find_element(By.ID, "TextBox2").send_keys("123")
  driver.find_element(By.ID, "Button1").click()
  time.sleep(2)

  cookid = driver.get_cookies()
  # print("cookies",cookid[0]['value'])
  cookid = cookid[0]['value']
  time.sleep(2)
  GLOBLE_COOKIE = f"ASP.NET_SessionId={cookid}"
  # print("cookids",GLOBLE_COOKIE)
  # driver.quit()


# -*- coding:utf-8 -*-
'''
月份计算：判断指定月份是大月、小月还是平月以及多少天
'''
# 大月
big_month = [1, 3, 5, 7, 8, 10, 12]
# 小月
small_month = [4, 6, 9, 11]
# 平月
flat_month = [2]


def compute_day_month(m):
  """
    判断指定的月份是大月、小月还是平月
    :param m: 指定的月份
    :return: 返回一个字典：包含月份的天数、月份的类型
    """
  # print('>>>>>开始计算指定的月份：%s的信息<<<<<' % (m, ))
  # 返回的数据
  out_data = {'code': 0, 'msg': 'success'}
  if m in big_month:
    # 大月
    out_data['days'] = 31
    out_data['type'] = 'Big Month'
  elif m in small_month:
    # 小月
    out_data['days'] = 30
    out_data['type'] = 'Small Month'
  elif m in flat_month:
    # 平月
    out_data['type'] = 'Flat Month'
    # 平月天数：闰年29天，平年28天
    year = datetime.today().year
    print('>>>>>年份信息是：%s<<<<<' % (year,))
    if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
      # 闰年
      out_data['days'] = 29
    else:
      out_data['days'] = 28
  else:
    # 其他数据都是错误的
    out_data['code'] = -1
    out_data['msg'] = '数据异常，月份信息有误'
  return out_data


def Main(month, FilmType, FilmSize):
  # V8491 8491 8520
  dict = {1: "V8401", 2: "V8432", 3: "V8460", 4: "V8491", 5: "V8521"}
  print(dict[month])
  rst = re.search('\d+', dict[month])
  print(rst.group())
  Todaymonth = datetime.today().month
  GET_Cookies()
  GET_VIEWSTATE_Function()
  if (Todaymonth - month == 0):
    for a in range(compute_day_month(month)['days']):
      print(a)
      a = a + int(rst.group())
      POST_VIEWSTATE_Function_day('ctl00$ContentPlaceHolder1$Calendar1', a)
      POST_VIEWSTATE_Function_day('ctl00$ContentPlaceHolder1$Calendar2', a)
      POST_Search(FilmType, FilmSize)

    print("1")
  elif (Todaymonth - month > 0):
  
    monthsum = Todaymonth - month
    var = Todaymonth - monthsum
    for m_s in range(monthsum):
      POST_VIEWSTATE_Function_month('ctl00$ContentPlaceHolder1$Calendar1', dict[Todaymonth - (m_s + 1)])
      POST_VIEWSTATE_Function_month('ctl00$ContentPlaceHolder1$Calendar2', dict[Todaymonth - (m_s + 1)])
    print("2")

    for a in range(compute_day_month(month)['days']):
     print("a=",a,"compute=", compute_day_month(month)['days'])
     a = a + int(rst.group())
     POST_VIEWSTATE_Function_day('ctl00$ContentPlaceHolder1$Calendar1', a)
     POST_VIEWSTATE_Function_day('ctl00$ContentPlaceHolder1$Calendar2', a)
     POST_Search(FilmType, FilmSize)

  EXCEL_FUNCTION(result, FilmType, FilmSize)
  global sum
  result.clear()
  sum = 0


Main(5,"影像科","14INX17IN")

Main(5, "影像科彩打", "13INX17IN")

Main(5,"放射科","11INX14IN")

Main(5,"放射科","14INX17IN")

Main(5,"体检","11INX14IN")
